// utils/aiGradingService.js
// AI批改服务

const CONFIG = require('./config');

const AI_CONFIG = {
  // 可以配置不同的AI服务
  OPENAI: {
    API_KEY: 'your_openai_api_key',
    BASE_URL: 'https://api.openai.com/v1',
    MODEL: 'gpt-3.5-turbo'
  },
  // 本地AI服务配置 - 指向Action-ai模块
  LOCAL_AI: {
    BASE_URL: CONFIG.getAIBaseUrl() + '/ai'
  }
};

class AIGradingService {
  constructor() {
    this.standardAnswers = this.loadStandardAnswers();
  }

  // 加载标准答案库
  loadStandardAnswers() {
    return {
      calculation: {
        patterns: [
          { pattern: /(\d+)\s*\+\s*(\d+)/, solver: (a, b) => parseInt(a) + parseInt(b) },
          { pattern: /(\d+)\s*-\s*(\d+)/, solver: (a, b) => parseInt(a) - parseInt(b) },
          { pattern: /(\d+)\s*×\s*(\d+)/, solver: (a, b) => parseInt(a) * parseInt(b) },
          { pattern: /(\d+)\s*÷\s*(\d+)/, solver: (a, b) => parseInt(a) / parseInt(b) }
        ]
      },
      knowledge: {
        '北京是中国的': '首都',
        '中国的首都是': '北京',
        '1+1等于': '2',
        '太阳从哪里升起': '东方',
        '地球有几个月亮': '1个'
      },
      choice: {
        '质数': ['2', '3', '5', '7', '11', '13', '17', '19'],
        '偶数': ['2', '4', '6', '8', '10', '12', '14', '16'],
        '奇数': ['1', '3', '5', '7', '9', '11', '13', '15']
      }
    };
  }

  // 计算题自动批改
  gradeCalculation(question, studentAnswer) {
    const questionText = question.question;
    const patterns = this.standardAnswers.calculation.patterns;
    
    for (let pattern of patterns) {
      const match = questionText.match(pattern.pattern);
      if (match) {
        const correctAnswer = pattern.solver(match[1], match[2]);
        const isCorrect = Math.abs(parseFloat(studentAnswer) - correctAnswer) < 0.01;
        
        return {
          isCorrect,
          correctAnswer: correctAnswer.toString(),
          explanation: isCorrect ? '计算正确' : `正确答案是 ${correctAnswer}`
        };
      }
    }
    
    return {
      isCorrect: false,
      correctAnswer: '无法自动判断',
      explanation: '题目格式无法识别，需要人工批改'
    };
  }

  // 填空题批改
  gradeFillInBlank(question, studentAnswer) {
    const questionText = question.question.toLowerCase();
    const studentAns = studentAnswer.toLowerCase().trim();
    
    // 检查知识库
    for (let [key, value] of Object.entries(this.standardAnswers.knowledge)) {
      if (questionText.includes(key.toLowerCase())) {
        const isCorrect = studentAns === value.toLowerCase();
        return {
          isCorrect,
          correctAnswer: value,
          explanation: isCorrect ? '答案正确' : `正确答案是：${value}`
        };
      }
    }
    
    return {
      isCorrect: false,
      correctAnswer: '需要人工批改',
      explanation: '无法自动判断，建议人工批改'
    };
  }

  // 选择题批改
  gradeChoice(question, studentAnswer) {
    const questionText = question.question;
    const options = question.options || [];
    
    // 简单的选择题批改逻辑
    if (options.length > 0) {
      const correctOption = options.find(opt => opt.isCorrect);
      if (correctOption) {
        const isCorrect = studentAnswer === correctOption.text;
        return {
          isCorrect,
          correctAnswer: correctOption.text,
          explanation: isCorrect ? '选择正确' : `正确答案是：${correctOption.text}`
        };
      }
    }
    
    return {
      isCorrect: false,
      correctAnswer: '需要人工批改',
      explanation: '无法自动判断选择题答案'
    };
  }

  // 批改单个题目
  gradeSingleQuestion(question) {
    const { type, studentAnswer } = question;
    
    if (!studentAnswer || studentAnswer.trim() === '') {
      return {
        isCorrect: false,
        correctAnswer: '未作答',
        explanation: '学生未作答',
        score: 0
      };
    }
    
    let result;
    switch (type) {
      case 'calculation':
        result = this.gradeCalculation(question, studentAnswer);
        break;
      case 'fillInBlank':
        result = this.gradeFillInBlank(question, studentAnswer);
        break;
      case 'choice':
        result = this.gradeChoice(question, studentAnswer);
        break;
      default:
        result = {
          isCorrect: false,
          correctAnswer: '需要人工批改',
          explanation: '未知题目类型，需要人工批改'
        };
    }
    
    // 计算分数
    result.score = result.isCorrect ? (question.score || 1) : 0;
    
    return result;
  }

  // 批改多个题目
  async gradeQuestions(questions) {
    const results = [];
    let totalScore = 0;
    let maxScore = 0;
    
    for (let question of questions) {
      const result = this.gradeSingleQuestion(question);
      results.push({
        ...question,
        ...result
      });
      
      totalScore += result.score;
      maxScore += (question.score || 1);
    }
    
    return {
      questions: results,
      totalScore,
      maxScore,
      percentage: maxScore > 0 ? Math.round((totalScore / maxScore) * 100) : 0,
      gradedAt: new Date().toISOString()
    };
  }

  // 调用真实的AI批改服务
  async gradeWithAI(ocrText, options = {}) {
    try {
      const {
        subject = '数学',
        gradingCriteria = '请仔细检查计算过程和答案的正确性',
        useLocalAI = true
      } = options;

      if (!ocrText || ocrText.trim() === '') {
        throw new Error('OCR文本不能为空');
      }

      console.log('开始调用AI批改服务...', { ocrText, subject, gradingCriteria });

      // 调用后端AI批改接口
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${AI_CONFIG.LOCAL_AI.BASE_URL}/grade`,
          method: 'POST',
          data: {
            ocrText: ocrText,
            subject: subject,
            gradingCriteria: gradingCriteria
          },
          header: {
            'Content-Type': 'application/json'
          },
          timeout: 30000, // 30秒超时
          success: (res) => {
            console.log('AI批改接口响应:', res);
            resolve(res);
          },
          fail: (error) => {
            console.error('AI批改接口调用失败:', error);
            reject(error);
          }
        });
      });

      // 处理响应
      if (response.statusCode === 200 && response.data) {
        if (response.data.success) {
          return {
            success: true,
            data: {
              ...response.data.data,
              aiGenerated: true,
              gradedAt: new Date().toISOString()
            }
          };
        } else {
          throw new Error(response.data.error || 'AI批改失败');
        }
      } else {
        throw new Error(`HTTP错误: ${response.statusCode}`);
      }

    } catch (error) {
      console.error('AI批改过程中发生错误:', error);
      
      // 如果AI批改失败，可以选择回退到本地批改
      console.log('AI批改失败，尝试使用本地批改逻辑...');
      
      try {
        // 尝试从OCR文本中解析题目
        const questions = this.parseOCRToQuestions(ocrText);
        const localResult = await this.gradeQuestions(questions);
        
        return {
          success: true,
          data: {
            ...localResult,
            aiGenerated: false,
            fallbackReason: '使用本地批改逻辑',
            originalError: error.message
          }
        };
      } catch (fallbackError) {
        return {
          success: false,
          error: `AI批改失败: ${error.message}，本地批改也失败: ${fallbackError.message}`
        };
      }
    }
  }

  // 解析OCR文本为题目格式（简单实现）
  parseOCRToQuestions(ocrText) {
    const questions = [];
    const lines = ocrText.split('\n').filter(line => line.trim());
    
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim();
      
      // 简单的题目识别逻辑
      if (line.match(/\d+[\.\)]\s*/) || line.includes('=') || line.includes('？') || line.includes('?')) {
        // 尝试识别计算题
        if (line.match(/\d+\s*[+\-×÷]\s*\d+/)) {
          questions.push({
            type: 'calculation',
            question: line,
            studentAnswer: '', // OCR可能需要进一步解析学生答案
            score: 10
          });
        } else {
          // 其他类型题目
          questions.push({
            type: 'fillInBlank',
            question: line,
            studentAnswer: '',
            score: 10
          });
        }
      }
    }
    
    // 如果没有识别到题目，创建一个通用题目
    if (questions.length === 0) {
      questions.push({
        type: 'fillInBlank',
        question: ocrText,
        studentAnswer: '',
        score: 100
      });
    }
    
    return questions;
  }

  // 主要的批改入口
  async grade(questions, useAI = false) {
    try {
      if (useAI) {
        return await this.gradeWithAI(questions);
      } else {
        return await this.gradeQuestions(questions);
      }
    } catch (error) {
      console.error('批改过程中发生错误:', error);
      return {
        success: false,
        error: error.message || '批改过程中发生未知错误'
      };
    }
  }
}

// 导出单例
const aiGradingService = new AIGradingService();
module.exports = aiGradingService;